package Game;

import javax.sound.sampled.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;

public class GameClient extends Frame {
    public static final int WORLD_WIDTH = 960;
    public static final int WORLD_HEIGHT = 720;
    private Image offScreenImage;
    private World world;
    private Image backgroundImage;
    private Clip backgroundMusic;
    private boolean isMusicPlaying = false;

    public GameClient(boolean Doubleplayer) {
        this.world = new World(WORLD_WIDTH, WORLD_HEIGHT, Doubleplayer);
        offScreenImage = null;

        // 加载背景图片
        try {
            backgroundImage = ImageIO.read(getClass().getResource("/images/setimage.png"));
        } catch (IOException e) {
            System.err.println("无法加载背景图片: " + e.getMessage());
        }

        // 加载背景音乐
        loadBackgroundMusic();
    }

    private void loadBackgroundMusic() {
        try {
            URL musicUrl = getClass().getResource("/music/backgroundmusic.wav");
            if (musicUrl == null) {
                System.err.println("找不到背景音乐文件");
                return;
            }

            AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(musicUrl);
            AudioFormat format = audioInputStream.getFormat();
            DataLine.Info info = new DataLine.Info(Clip.class, format);

            if (!AudioSystem.isLineSupported(info)) {
                System.err.println("不支持的音频格式");
                return;
            }

            backgroundMusic = (Clip) AudioSystem.getLine(info);
            backgroundMusic.open(audioInputStream);

            // 设置音量（可选）
            if (backgroundMusic.isControlSupported(FloatControl.Type.MASTER_GAIN)) {
                FloatControl gainControl = (FloatControl) backgroundMusic.getControl(FloatControl.Type.MASTER_GAIN);
                gainControl.setValue(-10.0f); // 降低10分贝
            }

            backgroundMusic.loop(Clip.LOOP_CONTINUOUSLY);
            startBackgroundMusic();

        } catch (UnsupportedAudioFileException | IOException | LineUnavailableException e) {
            System.err.println("加载背景音乐时出错: " + e.getMessage());
        }
    }

    public void startBackgroundMusic() {
        if (backgroundMusic != null && !isMusicPlaying) {
            backgroundMusic.start();
            isMusicPlaying = true;
        }
    }

    public void stopBackgroundMusic() {
        if (backgroundMusic != null && isMusicPlaying) {
            backgroundMusic.stop();
            isMusicPlaying = false;
        }
    }

    private class PaintThread implements Runnable {
        public void run() {
            while(true) {
                repaint();
                try {
                    Thread.sleep(30);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void paint(Graphics g) {
        if(!world.End())
            world.drawWorld(g);
        else {
            world.drawEnd(g);
        }
    }

    public void update(Graphics g) {
        if(offScreenImage == null) {
            offScreenImage = this.createImage(WORLD_WIDTH, WORLD_HEIGHT);
        }
        Graphics gOffScreen = offScreenImage.getGraphics();

        // 绘制背景
        if (backgroundImage != null) {
            gOffScreen.drawImage(backgroundImage, 0, 0, WORLD_WIDTH, WORLD_HEIGHT, null);
        } else {
            gOffScreen.setColor(Color.BLUE);
            gOffScreen.fillRect(0, 0, WORLD_WIDTH, WORLD_HEIGHT);
        }

        paint(gOffScreen);
        g.drawImage(offScreenImage, 0, 0, null);
    }

    public void lauchFrame() {
        this.setLocation(400, 300);
        this.setSize(WORLD_WIDTH, WORLD_HEIGHT);
        this.setTitle("ZombieCrisis");
        this.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                stopBackgroundMusic();
                System.exit(0);
            }
        });
        this.setResizable(false);
        this.addKeyListener(new KeyMonitor((Hero) world.getObject(0)));
        if(world.getObject(1) instanceof Hero)
            this.addKeyListener(new KeyMonitor((Hero) world.getObject(1)));
        setVisible(true);
        new Thread(new PaintThread()).start();
    }

    private class KeyMonitor extends KeyAdapter {
        Hero hero;
        public KeyMonitor(Hero hero){
            this.hero = hero;
        }
        public void keyReleased(KeyEvent e) {
            this.hero.keyReleased(e);
        }
        public void keyPressed(KeyEvent e) {
            this.hero.KeyPressed(e);
        }
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> {
            GameClient client = new GameClient(true); // 双人模式
            client.lauchFrame();
        });
    }
}